package com.apache.rpc;

import com.apache.rpc.common.RpcUtil;
import com.apache.rpc.tomcat.RpcServerFilter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ImportResource;
import org.springframework.web.filter.CharacterEncodingFilter;

@ImportResource("classpath:spring-context.xml")
@SpringBootApplication
@EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class,
        HibernateJpaAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class})
@EnableEurekaClient
@EnableDiscoveryClient
public class RpcServerApplication {

    public static void main(String[] args) {
        SpringApplication application = new SpringApplication(RpcServerApplication.class);
//        String sockePort = RpcUtil.getInstance().getValueByKey("rpc_service_port");
//        application.addListeners(new StartSocketPortListener(sockePort));
        application.run(args);
    }

    @Bean
    public StartSocketPortListener startSocketPortListener() {
        String sockePort = RpcUtil.getInstance().getValueByKey("rpc_service_port");
        StartSocketPortListener listener =  new StartSocketPortListener(sockePort);
        listener.registry();
        return listener;
    }

    @Bean
    public FilterRegistrationBean encodingFilter() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new CharacterEncodingFilter());
        registration.addUrlPatterns("/*");
        registration.addInitParameter("encoding", "UTF-8");
        registration.addInitParameter("forceEncoding", "true");
        registration.setName("encodingFilter");
        registration.setOrder(1);
        return registration;
    }

    @Bean
    public FilterRegistrationBean ssoServerFilter() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new RpcServerFilter());
        registration.addUrlPatterns("/*");
        registration.setName("rpcServerFilter");
        registration.setOrder(2);
        return registration;
    }
}
